package com.yq.ylmall.activity.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yq.ylmall.activity.service.ICouponScopeService;
import com.yq.ylmall.activity.service.IExchangeCodeService;
import com.yq.ylmall.dto.activity.CouponFormDto;
import com.yq.ylmall.dto.activity.CouponIssueFormDto;
import com.yq.ylmall.dto.activity.CouponQueryDto;
import com.yq.ylmall.enums.activity.CouponStatus;
import com.yq.ylmall.enums.activity.ObtainType;
import com.yq.ylmall.exception.ServiceException;
import com.yq.ylmall.model.activity.Coupon;
import com.yq.ylmall.activity.mapper.CouponMapper;
import com.yq.ylmall.activity.service.ICouponService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yq.ylmall.model.activity.CouponScope;
import com.yq.ylmall.result.ResultCode;
import com.yq.ylmall.vo.activity.CouponPageVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;


import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 优惠券的规则信息 服务实现类
 * </p>
 *
 * @author cherry
 * @since 2024-06-13
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class CouponServiceImpl extends ServiceImpl<CouponMapper, Coupon> implements ICouponService {
    private final ICouponScopeService couponScopeService; //优惠卷的限定范围业务类
    private final IExchangeCodeService exchangeCodeService; // 兑换码的业务类
    @Override
    public void saveCoupon(CouponFormDto couponFormDto) {
        couponFormDto.setDiscountValue(couponFormDto.getDiscountValue()*100);
        couponFormDto.setThresholdAmount(couponFormDto.getThresholdAmount()*100);
        couponFormDto.setMaxDiscountAmount(couponFormDto.getMaxDiscountAmount()*100);
        Coupon coupon = new Coupon();

        BeanUtils.copyProperties(couponFormDto,coupon);
        this.save(coupon);
        if (!couponFormDto.getSpecific()){
            return;
        }
        List<Long> scopes = couponFormDto.getScopes();
        if (CollUtil.isEmpty(scopes)) {
            throw new ServiceException("分类id不能为空",444);
        }
        List<CouponScope> scopeList = scopes
                .stream()
                .map(id -> new CouponScope().setCouponId(coupon.getId()).setBizId(id).setType(1)).collect(Collectors.toList());
        couponScopeService.saveBatch(scopeList);
    }

    @Override
    public IPage<CouponPageVO> selectCouponPage(CouponQueryDto couponQueryDto) {
        IPage<Coupon> page = new Page<>(couponQueryDto.getPageNum(), couponQueryDto.getPageSize());
        LambdaQueryWrapper<Coupon> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(couponQueryDto.getType()!=null,Coupon::getDiscountType,couponQueryDto.getType())
                .eq(couponQueryDto.getStatus()!=null,Coupon::getStatus,couponQueryDto.getStatus())
                .like(StrUtil.isNotBlank(couponQueryDto.getName()),Coupon::getName,couponQueryDto.getName())
                .orderByDesc(Coupon::getCreateTime);
        page = baseMapper.selectPage(page, wrapper);
        List<Coupon> records = page.getRecords();

        if (CollUtil.isEmpty(records)){
            throw new ServiceException("查询出问题啦！",445);
        }
        List<CouponPageVO> list = records
                .stream()
                .map(coupon -> BeanUtil.copyProperties(coupon, CouponPageVO.class))
                .collect(Collectors.toList());
        IPage<CouponPageVO> result = new Page<>();
        return result.setRecords(list);
    }

    @Override
    public void issueCoupon(Long id, CouponIssueFormDto couponIssueFormDto) {
        log.info("发放优惠卷  线程名:{}",Thread.currentThread().getName());
        if (id==null||!id.equals(couponIssueFormDto.getId())){
            throw new ServiceException(ResultCode.DATA_ERROR);
        }
        Coupon coupon = this.getById(id);
        if (ObjectUtil.isEmpty(coupon)){
            throw new ServiceException(ResultCode.THE_COUPON_DOES_NOT_EXIST);
        }
        if (coupon.getStatus()!= CouponStatus.DRAFT&&coupon.getStatus()!=CouponStatus.PAUSE){
            throw new ServiceException(ResultCode.DISCOUNT_COUPON_STATUS_ERROR);
        }
        DateTime now = DateTime.now();
        boolean isBeginIssue = couponIssueFormDto.getIssueBeginTime() == null || !couponIssueFormDto.getIssueBeginTime().after(now);

        Coupon couponDB = BeanUtil.copyProperties(couponIssueFormDto, Coupon.class);
        if (isBeginIssue){
            couponDB.setStatus(CouponStatus.ISSUING);
            couponDB.setIssueBeginTime(now);
        } else {
            couponDB.setStatus(CouponStatus.UN_ISSUE);
        }
        this.updateById(couponDB);

        //如果优惠卷的领取方式为 指定发放 且 优惠卷之前的状态是待发放，需要生成兑换码
        if (coupon.getObtainWay() == ObtainType.ISSUE && coupon.getStatus() == CouponStatus.DRAFT){
            //兑换码兑换的截止时间，就是优惠卷领取的截止时间。该时间从前端传的封装到couponDB中了
            coupon.setIssueEndTime(couponDB.getIssueEndTime());
            //异步生成兑换码
            exchangeCodeService.asyncGenerateExchangeCode(coupon);
        }
    }
}


